package com.czmh.etc.onlinepubsys.controller.ue;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.czmh.etc.onlinepubsys.constants.ue.BusinessType;
import com.czmh.etc.onlinepubsys.entity.mingchuang.CurrentContext;
import com.czmh.etc.onlinepubsys.entity.mingchuang.EtcOrder;
import com.czmh.etc.onlinepubsys.json.cmg.JSONResult;
import com.czmh.etc.onlinepubsys.model.EtcPayOrder;
import com.czmh.etc.onlinepubsys.request.ue.ActFinishRequest;
import com.czmh.etc.onlinepubsys.request.ue.NoInsuranceOrderReviewRequest;
import com.czmh.etc.onlinepubsys.request.ue.ObeSamRequest;
import com.czmh.etc.onlinepubsys.request.ue.ReqActiveRequest;
import com.czmh.etc.onlinepubsys.response.ue.ApiResponse;
import com.czmh.etc.onlinepubsys.services.EtcOrderService;
import com.czmh.etc.onlinepubsys.services.EtcPayOrderService;
import com.czmh.etc.onlinepubsys.services.mingchuang.ICurrentContextService;
import com.czmh.etc.onlinepubsys.services.mingchuang.IObuService;
import com.czmh.etc.onlinepubsys.utils.RedisUtil;
import com.czmh.etc.onlinepubsys.utils.ue.UeHttpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@Slf4j
@RestController
@RequestMapping("/{version}/api/ue/active")
@Api(tags = "4.4 设备激活接口相关 -联合电子")
public class UeActiveController {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ICurrentContextService currentContextService;

    @Autowired
    private EtcPayOrderService etcPayOrderService;

    @Autowired
    private EtcOrderService etcOrderService;

    @Autowired
    private IObuService obuService;

    @PostMapping("/reqActive")
    @ApiOperation("4.4.1卡签激活申请（产品二发）")
    public JSONResult reqActive(@RequestBody ReqActiveRequest req) {
        log.info("reqActive:{}", JSON.toJSONString(req));
        String token = redisUtil.queryUeToken();
        JSONResult result = new JSONResult();
        ApiResponse r = UeHttpUtil.post(BusinessType.REQ_ACTIVE, JSON.toJSONString(req), token);
        if (r != null && r.getSuccess()) {
            if (r.getSuccess()) {
                result.setRspData(r.getRspData());
                result.setMessage(r.getMsg());
                CurrentContext currentContext = currentContextService.getByOrderNo(req.getOrderId());
                String jsonStr = currentContext.getJsonData();
                JSONObject jsonObject = JSON.parseObject(jsonStr);
                if(jsonObject == null){
                    jsonObject = new JSONObject();
                }
                jsonObject.put("reqActiveRequest", req);
                currentContext.setJsonData(jsonObject.toJSONString());
                currentContextService.update(currentContext);
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r != null ? r.getMsg() : "服务器开小差，请稍后再试！");
        }
        return result;
    }

    @PostMapping("/obeSam")
    @ApiOperation("4.4.2卡签激活申请（产品二发）")
    public JSONResult obeSam(@RequestBody ObeSamRequest req) {
        log.info("obeSam:{}", JSON.toJSONString(req));
        String token = redisUtil.queryUeToken();
        JSONResult result = new JSONResult();
        ApiResponse r = UeHttpUtil.post(BusinessType.OBE_SAM, JSON.toJSONString(req), token);
        if (r != null) {
            result.setRspData(r.getRspData());
            result.setMessage(r.getMsg());
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r != null ? r.getMsg() : "服务器开小差，请稍后再试！");
        }
        return result;
    }

    @PostMapping("/actFinish")
    @ApiOperation("4.4.12激活结果确认接口")
    public JSONResult actFinish(@RequestBody ActFinishRequest req) {
        log.info("actFinish:{}", JSON.toJSONString(req));
        String token = redisUtil.queryUeToken();
        JSONResult result = new JSONResult();
        ApiResponse r = UeHttpUtil.post(BusinessType.ACT_FINISH, JSON.toJSONString(req), token);
        if (r != null && r.getSuccess()) {
            if (r.getSuccess()) {
                result.setRspData(r.getRspData());
                result.setMessage(r.getMsg());

                //激活确认成功之后更新对应的信息
                CurrentContext currentContext = currentContextService.getByOrderNo(req.getOrderId());
                currentContext.setState(5);
                currentContext.setObuId(req.getObuId());
                currentContext.setEtcCardNo(req.getCarNo());
                currentContextService.update(currentContext);
                //按照铭创流程逻辑操作激活成功之后的操作
                obuService.cmgActiveComplete(currentContext.getObuId(), currentContext.getUserId());

                //激活成功后判断是否有订金订单，有的话则直接把订单设置成待审核状态
                QueryWrapper<EtcPayOrder> wrapper = new QueryWrapper<>();
                LambdaQueryWrapper<EtcPayOrder> lambda = wrapper.lambda();
                lambda.eq(EtcPayOrder::getDeleteFlag, 0);
                lambda.eq(EtcPayOrder::getOrderSn, currentContext.getOrderNo());
                EtcPayOrder etcPayOrder = etcPayOrderService.getOne(wrapper, true);
                if(etcPayOrder != null){
                    etcPayOrder.setPayState(2);
                    etcPayOrder.setRefundApplyTime(new Date());
                    etcPayOrder.setUpdatedTime(new Date());
                    etcPayOrderService.updateById(etcPayOrder);
                }
                //激活成功后判断是否有前置订金订单，有的话则直接把订单设置成待审核状态，等待管理员审核之后给用户全额退款
                EtcOrder etcOrder = etcOrderService.queryByOrderNo(req.getOrderId());
                QueryWrapper<EtcPayOrder> queryWrapper = new QueryWrapper<>();
                LambdaQueryWrapper<EtcPayOrder> lambdaQueryWrapper = queryWrapper.lambda();
                lambdaQueryWrapper.eq(EtcPayOrder::getDeleteFlag, 0);
                lambdaQueryWrapper.eq(EtcPayOrder::getPayState, 0);
                lambdaQueryWrapper.eq(EtcPayOrder::getUserId, etcOrder.getUserId());
                lambdaQueryWrapper.eq(EtcPayOrder::getProductSn, etcOrder.getBody());
                EtcPayOrder payOrder = etcPayOrderService.getOne(queryWrapper, true);
                if(payOrder != null){
                    payOrder.setPayState(2);
                    payOrder.setRefundApplyTime(new Date());
                    payOrder.setUpdatedTime(new Date());
                    etcPayOrderService.updateById(etcPayOrder);
                }
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r != null ? r.getMsg() : "服务器开小差，请稍后再试！");
        }
        return result;
    }
}
